package com.app.aipass.fragment.my.paytype;

import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProviders;

import com.app.aipass.BR;
import com.app.aipass.R;
import com.app.aipass.app.AppViewModelFactory;
import com.app.aipass.databinding.FragmentMyPaytypeBinding;
import com.app.aipass.entity.Message;
import com.app.aipass.fragment.my.paytype.addpaytype.AddPayTypeFragment;
import com.app.aipass.utils.StatusBarUtil;
import com.app.aipass.utils.Utils;
import com.app.aipass.view.BaseDialog;
import com.app.aipass.view.ConfirmDialog;
import com.app.aipass.view.EmptyView;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import me.goldze.mvvmhabit.base.BaseFragment;
import me.goldze.mvvmhabit.bus.RxBus;
import me.goldze.mvvmhabit.bus.RxSubscriptions;
import me.tatarka.bindingcollectionadapter2.BindingRecyclerViewAdapter;

/**
 * @author: woking
 * @date: 2021/6/11
 * @description：
 */
public class PayTypeFragment extends BaseFragment<FragmentMyPaytypeBinding, PayTypeViewModel> {

    private Disposable mSubscription;

    @Override
    public void initParam() {
        super.initParam();
        getActivity().setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
    }

    @Override
    public int initContentView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return R.layout.fragment_my_paytype;
    }

    @Override
    public int initVariableId() {
        return BR.viewModel;
    }

    @Override
    public PayTypeViewModel initViewModel() {
        //使用自定义的ViewModelFactory来创建ViewModel，如果不重写该方法，则默认会调用NetWorkViewModel(@NonNull Application application)构造方法
        AppViewModelFactory factory = AppViewModelFactory.getInstance(getActivity().getApplication());
        return ViewModelProviders.of(this, factory).get(PayTypeViewModel.class);
    }
    @Override
    public void onDestroy() {
        super.onDestroy();
        if(mSubscription != null)
        {
            RxSubscriptions.remove(mSubscription);
        }
    }
    @Override
    public void initData() {
        binding.ivTitleBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                getActivity().finish();
            }
        });
        binding.tvConfirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(!Utils.isLogin())
                {
                    return;
                }
                boolean hasBank = false;
                boolean hasZFB = false;
                boolean hasWX = false;
                if(viewModel.observableList!=null)
                {
                    for(int i = 0; i < viewModel.observableList.size(); i++)
                    {
                        if(viewModel.observableList.get(i).entity.get().type == 1)  hasBank = true;
                        else if(viewModel.observableList.get(i).entity.get().type == 2) hasZFB = true;
                        else if(viewModel.observableList.get(i).entity.get().type == 3) hasWX = true;
                    }
                }
                Bundle bundle = new Bundle();
                bundle.putBoolean("hasBank",hasBank);
                bundle.putBoolean("hasZFB",hasZFB);
                bundle.putBoolean("hasWX",hasWX);
                startContainerActivity(AddPayTypeFragment.class.getCanonicalName(),bundle);
            }
        });

        mSubscription = RxBus.getDefault().toObservable(Message.class)
                .observeOn(AndroidSchedulers.mainThread()) //回调到主线程更新UI
                .subscribe(new Consumer<Message>() {
                    @Override
                    public void accept(final Message message) throws Exception {
                        Log.e("TAG","===============message=============="+message.getName());
                        if(message.getName().equals("update_pay_type"))
                        {
                            //请求网络数据
                            viewModel.requestNetWork(false);
                        }
                    }
                });
        //将订阅者加入管理站
        RxSubscriptions.add(mSubscription);


        binding.mRecyclerView.setEmptyView(new EmptyView(getActivity()));
        //给RecyclerView添加Adpter，请使用自定义的Adapter继承BindingRecyclerViewAdapter，重写onBindBinding方法，里面有你要的Item对应的binding对象。
        // Adapter属于View层的东西, 不建议定义到ViewModel中绑定，以免内存泄漏
        binding.setAdapter(new BindingRecyclerViewAdapter());
        //请求网络数据
        viewModel.requestNetWork(false);


        initRefreshLayout();
    }
    private void initRefreshLayout()
    {
        binding.twinklingRefreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                viewModel.onRefresh();
            }
        });
        binding.twinklingRefreshLayout.setEnableLoadMore(false);
        binding.twinklingRefreshLayout.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                viewModel.onLoadMore();
            }
        });
//        binding.twinklingRefreshLayout.autoRefresh();
    }

    @Override
    public void initViewObservable() {
        //监听下拉刷新完成
        viewModel.uc.finishRefreshing.observe(this, new Observer() {
            @Override
            public void onChanged(@Nullable Object o) {
                //结束刷新
                binding.twinklingRefreshLayout.finishRefresh();
//                viewModel.dismissDialog();
                if(viewModel.observableList.size() >= 3)
                {
                    binding.tvConfirm.setVisibility(View.GONE);
                }
                else
                {
                    binding.tvConfirm.setVisibility(View.VISIBLE);
                }
            }
        });
        //监听上拉加载完成
        viewModel.uc.finishLoadmore.observe(this, new Observer() {
            @Override
            public void onChanged(@Nullable Object o) {
                //结束刷新
                binding.twinklingRefreshLayout.finishLoadMore();
//                viewModel.dismissDialog();
            }
        });
//        //监听删除条目
//        viewModel.deleteItemLiveData.observe(this, new Observer<PayTypeItemViewModel>() {
//            @Override
//            public void onChanged(PayTypeItemViewModel netWorkItemViewModel) {
//                int index = viewModel.getItemPosition(netWorkItemViewModel);
//                //删除选择对话框
//                MaterialDialogUtils.showBasicDialog(getContext(), "提示", "是否删除【" + netWorkItemViewModel.entity.get().getName() + "】？ position：" + index)
//                        .onNegative(new MaterialDialog.SingleButtonCallback() {
//                            @Override
//                            public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
//                                ToastUtils.showShort("取消");
//                            }
//                        }).onPositive(new MaterialDialog.SingleButtonCallback() {
//                    @Override
//                    public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
//                        viewModel.deleteItem(netWorkItemViewModel);
//                    }
//                }).show();
//            }
//        });

        viewModel.editItemLiveData.observe(this, new Observer<PayTypeItemViewModel>() {
            @Override
            public void onChanged(PayTypeItemViewModel model) {
                Log.e("TAG", model.getPosition()+"=============onClickBuySell=================");
                ConfirmDialog dialog = new ConfirmDialog(getActivity());
                dialog.setTitle("提示");
                dialog.setMessage("是否要删除改支付方式？");
                dialog.setCancelable(false);
                dialog.setYesOnclickListener("确定", new BaseDialog.OnYesClickListener() {
                    @Override
                    public void onYesClick() {
                        dialog.dismiss();
                        viewModel.deleteOtcPayCccount(model.entity.get().id+"");
                    }
                });
                dialog.setCancleClickListener("取消", new BaseDialog.OnCloseClickListener() {
                    @Override
                    public void onCloseClick() {
                    }
                });
                dialog.show();
            }
        });
    }
}